﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using Newtonsoft.Json;

namespace UFrameWork
{
    /// <summary>
    /// Session
    /// </summary>
    public class USession : AppSession<USession>
    {
        private StringBuilder sendBuilder = new StringBuilder();

        public HeartBeat Beat;

        public USession()
        {
            Charset = Encoding.UTF8;
            Beat = new HeartBeat(this);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        public override void Send(string key)
        {
            this.Send(key,null);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        public override void Send(string key,params object[] data)
        {
            sendBuilder.Clear();
            sendBuilder.Append("{key:'");
            sendBuilder.Append(key);
            sendBuilder.Append("',data:");
            sendBuilder.Append(JsonConvert.SerializeObject(data));
            sendBuilder.Append("}");
            UWork.Do(UEvent.SERVER_SEND_MSG, this, sendBuilder.ToString());
            sendBuilder.Append(UReceiveFilter.EndFlag);
            
            byte[] bytes = Encoding.UTF8.GetBytes(sendBuilder.ToString());
            base.Send(bytes, 0, bytes.Length);
        }

        /// <summary>
        /// 发送字符串
        /// </summary>
        public void SendString(string msg)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(msg);
            base.Send(bytes, 0, bytes.Length);
        }
    }
}